# -*- coding: utf-8 -*-

import sys
import cStringIO

from base import BaseHandler

class WsgiHandler(BaseHandler):
	data = ''
	def __call__(self, environ, start_response, exc_info=None):
		""" Preparation stage. We need to check applicaion file existance
		import it, import application class  and create a class instance"""
		self.environ = environ
		self.start_response = start_response
		if(not self.environ.has_key('renyare.config')):
			raise self._err("No config variable")
		# Test is application has mode and action
		test = self.module.split(':')
		if(len(test) == 1): # Usual application with default class name
			(module_name, class_name) = ( self.module, self.module.split('.')[-1].title() )
		elif(len(test) == 2): # Application with action or alternate class name
			(module_name, class_name) = test
		else:
			self._err("Wrong module name: " +self.module)
		try:
			app_name = self.environ['renyare.config'].get('renyare', 'application')
			module = __import__(app_name+'.'+module_name, globals(), locals(), [''])  # Import submodule
			app_class = getattr(module, class_name) 	# Import class from module
		except:
			self._err("Error preparing %s application: %s" % (self.module_type, str(sys.exc_info()[1])))
		if(self.orig_app): 		# Application is wsgi middleware
			try: 			# Create class instance
				self.app = app_class(self.orig_app, config=params)
			except:
				try: 		# Not renyare-compatible middleware - passing only application
					self.app = app_class(self.orig_app)
				except:
					self._err("Error initialising middleware: arguments must be keywords")
		else:				# Application is wsgi application
			try: 			# Create class instance
				self.app = app_class(config=params)
			except:
				try: 		# Not renyare-compatible application
					self.app = app_class()
				except:
					self._err("Error initialising application: arguments must be keywords")
		try:
			app = self.app(environ, start_response)
		except:
			self._err("Error running %s application: %s" % (self.module_type, str(sys.exc_info()[1])))
		return app
